import { message, Modal } from 'antd';
import { updateBaseTeam } from '@/services/teamService';
import React, { PropsWithChildren } from 'react';
import { ProColumns, ProTable } from '@ant-design/pro-table';
import { TagType } from '@/models/tag';
import { TeamType } from '@/models/team';
import { UserType } from '@/models/user';

interface UpdateModalProps {
  oldData: TeamType.TeamVo;
  modalVisible: boolean;
  onSubmit: () => void;
  onCancel: () => void;
  loginUser: UserType.UserVO;
  tagMap: TagType.TagMap;
}

/**
 *  更新数据模型框
 * @param fields
 */
const updateBase = async (fields: TeamType.TeamUpdateBaseRequest) => {
  if ((fields?.userId || 0) <= 0) {
    message.loading('请先进行登入！');
    return [];
  }
  const hide = message.loading('正在修改');
  try {
    await updateBaseTeam({
      ...fields,
      id: fields.id,
      userId: fields.userId,
      teamTechnologyType: JSON.stringify(fields.teamTechnologyType),
    });
    hide();
    message.success('修改成功');
    return true;
  } catch (error) {
    hide();
    message.error('配置失败请重试');
    return false;
  }
};

/**
 *  更新数据模型框
 * @param props
 */
const UpdateTeam: React.FC<PropsWithChildren<UpdateModalProps>> = (props) => {
  const { oldData, modalVisible, onSubmit, onCancel, loginUser, tagMap } =
    props;
  /**
   * 根据分类获取标签选项数组
   */
  const getOptions = (category: string) => {
    // 判断是否存在于 tagMap列表中
    if (!category || !tagMap[category]) {
      return [];
    }
    return tagMap[category].map((tag) => {
      return {
        value: tag.tagName,
        label: tag.tagName,
      };
    });
  };
  /**
   * 表格列配置
   */
  const columns: ProColumns<TeamType.Team>[] = [
    {
      title: '队伍人数',
      dataIndex: 'maxNum',
      valueType: 'digit',
      fieldProps: {
        min: 3,
        max: 10,
      },
    },
    {
      title: '队伍类型',
      dataIndex: 'teamType',
      valueType: 'select',
      fieldProps: {
        options: getOptions('project'),
      },
    },
    {
      title: '技术类型',
      dataIndex: 'teamTechnologyType',
      valueType: 'treeSelect',
      fieldProps: {
        multiple: true,
        options: getOptions('technology'),
      },
    },
  ];

  return (
    <Modal
      destroyOnClose
      title="更新"
      open={modalVisible}
      onCancel={() => onCancel()}
      footer={null}
    >
      <ProTable<TeamType.Team, TeamType.Team>
        rowKey="id"
        type="form"
        columns={columns}
        form={{
          initialValues: oldData,
        }}
        onSubmit={async (value) => {
          const success = await updateBase({
            ...value,
            id: oldData.id,
            userId: loginUser?.id,
          });
          if (success) {
            onSubmit?.();
          }
        }}
      />
    </Modal>
  );
};

export default UpdateTeam;
